import { Video, Sequence, interpolate, Audio, useCurrentFrame } from 'remotion';
import VideoText from './VideoText';
import VideoSplitText from './VideoSplitText';
import React from 'react';
import { Fragment } from 'react';
// 导入默认视频文件
import video1 from '../assets/movies/check6s.mp4';
import video2 from '../assets/movies/check3s.mp4';
import video3 from '../assets/movies/check3s1.mp4';
import video4 from '../assets/movies/check6s2.mp4';
import video5 from '../assets/movies/check3s2.mp4';
import startVideo from '../assets/movies/female-start.mp4';
import endVideo from '../assets/movies/female-end.mp4';

// 导入默认音频文件
import audio1 from '../assets/audio/female-start.mp3';
import audio2 from '../assets/audio/female-002.mp3';
import audio3 from '../assets/audio/female-003.mp3';
import audio4 from '../assets/audio/female-004.mp3';
import audio5 from '../assets/audio/female-005.mp3';
import audio6 from '../assets/audio/female-006.mp3';
import audio7 from '../assets/audio/female-end.mp3';
import bgAudio from '../assets/audio/bg-m.mp3';

interface TextConfig {
  text?: string;
  style?: React.CSSProperties;
}

interface AudioConfig {
  audioUrl: string;
  startFrom?: number; // 相对于视频片段开始的时间(帧)
  duration: number; // 持续时间(帧)
  volume?: number; // 音量 0-1
}

interface VideoConfig {
  videoUrl?: string;
  audios?: AudioConfig[]; // 改为支持多个音频配置
  duration?: number;
  rotation?: number;
  transition?: {
    enabled?: boolean;
    duration?: number;
  };
}

interface MyVideoComponentProps {
  textConfigs?: TextConfig[];
  fps?: number;
  videoConfigs?: VideoConfig[];
}

export const MyVideoComponent: React.FC<MyVideoComponentProps> = ({
  textConfigs = [],
  fps = 30,
  videoConfigs = [],
}) => {
  const frame = useCurrentFrame();

  const AUDIO_BUFFER = 0.6 * fps;

  const TEXT_DELAY = 15; // 0.5秒 = 15帧

  // 将 defaultVideoData 移到组件内部
  const defaultVideoData = [
    {
      video: startVideo,
      audios: [
        {
          audioUrl: audio1,
          startFrom: 0, // 从视频片段开始播放
          duration: 3 * fps,
          volume: 1.0,
        },
      ],
      // text: '预算二十多万当然买林肯航海家了',
      highlightTexts: ['二十多万', '林肯航海家'],
      splitTexts: ['预算二十多万', '当然买林肯航海家了'],
      duration: 3 * fps,
      rotation: 0,
      transition: { enabled: true, duration: 8 },
    },
    {
      video: video1,
      audios: [
        {
          audioUrl: audio2,
          startFrom: 0,
          duration: 6 * fps,
          volume: 1.0,
        },
      ],
      duration: 6 * fps,
      highlightTexts: ['2.0T四缸280匹马力', '车长4米9'],
      splitTexts: [
        '别人的高配也不过是它的标配',
        '2.0T四缸280匹马力',
        '车长4米9突出一个气势',
      ],
      rotation: 0,
      transition: { enabled: true, duration: 8 },
    },
    {
      video: video2,
      audios: [
        {
          audioUrl: audio3,
          startFrom: 0,
          duration: 3 * fps,
          volume: 1.0,
        },
      ],
      // text: '这一米多环抱大连屏，设计师你是不是五行缺屏啊',
      highlightTexts: ['环抱大连屏'],
      splitTexts: ['这一米多环抱大连屏', '设计师你是不是五行缺屏啊'],
      duration: 3 * fps + AUDIO_BUFFER,
      rotation: 0,
      transition: { enabled: true, duration: 8 },
    },
    {
      video: video3,
      audios: [
        {
          audioUrl: audio4,
          startFrom: 0,
          duration: 3 * fps,
          volume: 1.0,
        },
      ],
      animation: true,
      text: '这座椅这么宽敞，还带电动调节，舒服',
      highlightTexts: ['电动调节'],
      splitTexts: ['这座椅这么宽敞', '还带电动调节', '舒服'],
      duration: 3 * fps + AUDIO_BUFFER,
      rotation: 0,
      transition: { enabled: true, duration: 8 },
    },
    {
      video: video4,
      audios: [
        {
          audioUrl: audio5,
          startFrom: 0,
          duration: 6 * fps,
          volume: 1.0,
        },
      ],
      highlightText: '360全景标配',
      // text: '360全景标配，一键泊车标配，盲区监测标配L2+驾驶辅助带车道居中，还能自动变道',
      splitTexts: [
        '360全景标配 一键泊车标配',
        '盲区监测标配',
        'L2+驾驶辅助带车道居中',
        '还能自动变道',
      ],
      highlightTexts: ['360全景', '一键泊车', 'L2+驾驶辅助', '自动变道'],
      duration: 6 * fps + AUDIO_BUFFER,
      rotation: 0,
      transition: { enabled: true, duration: 8 },
    },
    {
      video: video5,
      audios: [
        {
          audioUrl: audio6,
          startFrom: 0,
          duration: 3 * fps,
          volume: 1.0,
        },
      ],
      // text: '你不会花30w还买不到这样的品质吧',
      // highlightTexts: ['30w', '品质'],
      splitTexts: ['你不会花30w还买不到这样的品质'],
      duration: 3 * fps,
      rotation: 0,
      transition: { enabled: true, duration: 8 },
    },
    {
      video: endVideo,
      audios: [
        {
          audioUrl: audio7,
          startFrom: 0,
          duration: 3 * fps,
          volume: 1.0,
        },
      ],
      splitTexts: ['想知道最新落地价', '抓进来找我拿全系报价吧'],
      duration: 3 * fps,
      rotation: 0,
      transition: { enabled: true, duration: 8 },
    },
  ];

  // 合并默认数据和传入的配置
  const mergedVideoData = defaultVideoData.map((defaultItem, index) => {
    const customConfig = videoConfigs[index] || {};

    // 合并音频配置
    const mergedAudios = (customConfig.audios || defaultItem.audios || []).map(
      (audio) => ({
        ...audio,
        startFrom: audio.startFrom || 0,
        volume: audio.volume || 1.0,
      }),
    );

    // 计算最长的音频时间
    const maxAudioDuration = Math.max(
      ...mergedAudios.map((audio) => (audio.startFrom || 0) + audio.duration),
      0,
    );

    // 使用原始视频时长，不添加额外的缓冲时间
    const videoDuration = Math.ceil(
      Math.max(
        1,
        customConfig.duration || defaultItem.duration || maxAudioDuration,
      ),
    );

    return {
      ...defaultItem,
      video: customConfig.videoUrl || defaultItem.video,
      audios: mergedAudios,
      text: textConfigs[index]?.text || defaultItem.text,
      duration: videoDuration, // 使用原始时长
      rotation: customConfig.rotation ?? defaultItem.rotation,
      transition: customConfig.transition ?? defaultItem.transition,
    };
  });

  // 添加总时长计算
  const totalDuration = mergedVideoData.reduce(
    (acc, curr) => acc + curr.duration,
    0,
  );

  // 在组件返回之前添加验证
  if (totalDuration <= 0) {
    console.error('Total duration must be greater than 0');
    return null;
  }

  const getVideoStyle = (
    rotation: number,
    index: number,
    isLast: boolean,
  ): React.CSSProperties => {
    const baseStyle = {
      objectFit: (index === 0 || isLast ? 'contain' : 'cover') as
        | 'contain'
        | 'cover',
      backgroundColor: index === 0 || isLast ? 'black' : 'transparent',
      willChange: 'transform',
    };

    if (rotation % 180 !== 0) {
      return {
        ...baseStyle,
        width: '100vh',
        height: '100vw',
        position: 'absolute' as const,
        top: '50%',
        left: '50%',
        transform: `rotate(${rotation}deg) translate(-50%, -50%)`,
        transformOrigin: '0 0',
      };
    }

    return {
      ...baseStyle,
      width: '100%',
      height: '100%',
      transform: 'none',
    };
  };

  // 添加更平滑的缓动函数
  const easeInOutCubic = (t: number) => {
    return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  };

  const getTransitionStyles = (
    frame: number,
    start: number,
    currentVideoEnd: number,
    isLastVideo: boolean,
    videoTransition: VideoConfig['transition'],
  ) => {
    // 如果是最后一个视频或转场被禁用，不进行转场
    if (isLastVideo || !videoTransition?.enabled) {
      return {
        transform: 'translate3d(0, 0, 0)',
        willChange: 'transform',
      };
    }

    const transitionDuration = videoTransition.duration || 8;
    // 修改转场开始时间，确保在视频完整播放后再开始转场
    const transitionStart = start + currentVideoEnd - transitionDuration;

    // 只有在真正需要转场时才应用转场效果
    const isInTransition =
      frame >= transitionStart && frame < start + currentVideoEnd;

    if (!isInTransition) {
      return {
        transform: 'translate3d(0, 0, 0)',
        willChange: 'transform',
      };
    }

    const progress = interpolate(
      frame - transitionStart,
      [0, transitionDuration],
      [0, 1],
      {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
        easing: easeInOutCubic,
      },
    );

    return {
      transform: `translate3d(${-100 * progress}%, 0, 0)`,
      willChange: 'transform',
    };
  };

  const getNextVideoTransitionStyles = (
    frame: number,
    start: number,
    currentVideoEnd: number,
    videoTransition: VideoConfig['transition'],
  ) => {
    if (!videoTransition?.enabled) {
      return {
        display: 'none',
      };
    }

    const transitionDuration = videoTransition.duration || 8;
    const transitionStart = start + currentVideoEnd - transitionDuration;

    // 确保转场时机正确
    const isInTransition =
      frame >= transitionStart && frame < start + currentVideoEnd;

    if (!isInTransition) {
      return {
        transform: 'translate3d(100%, 0, 0)',
        willChange: 'transform',
      };
    }

    const progress = interpolate(
      frame - transitionStart,
      [0, transitionDuration],
      [0, 1],
      {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
        easing: easeInOutCubic,
      },
    );

    return {
      transform: `translate3d(${100 * (1 - progress)}%, 0, 0)`,
      willChange: 'transform',
    };
  };

  // 修改文字过渡效果函数
  const getTextTransitionStyles = (
    frame: number,
    start: number,
    currentVideoEnd: number,
    isLastVideo: boolean,
    videoTransition?: VideoConfig['transition'],
  ) => {
    const textStart = start + TEXT_DELAY;
    const transitionDuration = videoTransition?.duration || 8;

    const textEnd =
      isLastVideo || !videoTransition?.enabled
        ? start + currentVideoEnd
        : start + currentVideoEnd - transitionDuration;

    // 文字入场动画
    if (frame >= start && frame < textStart) {
      const enterProgress = interpolate(
        frame - start,
        [0, TEXT_DELAY],
        [0, 1],
        {
          extrapolateLeft: 'clamp',
          extrapolateRight: 'clamp',
          easing: easeInOutCubic,
        },
      );
      return {
        opacity: enterProgress,
        transform: `translateY(${20 * (1 - enterProgress)}px)`,
      };
    }

    // 文字退场动画
    if (frame >= textEnd && frame <= start + currentVideoEnd) {
      const exitProgress = interpolate(
        frame - textEnd,
        [0, transitionDuration],
        [0, 1],
        {
          extrapolateLeft: 'clamp',
          extrapolateRight: 'clamp',
          easing: easeInOutCubic,
        },
      );
      return {
        opacity: 1 - exitProgress,
        transform: `translateY(${20 * exitProgress}px)`,
      };
    }

    // 文字显示状态
    if (frame >= textStart && frame < textEnd) {
      return {
        opacity: 1,
        transform: 'translateY(0)',
      };
    }

    // 文字隐藏状态
    return {
      opacity: 0,
      transform: 'translateY(20px)',
    };
  };

  // 添加音量常量
  const BG_MUSIC_VOLUME = 0.7; // 背景音乐音量 30%
  const VOICE_VOLUME = 1.0; // 语音音量 100%

  return (
    <div
      style={{
        flex: 1,
        position: 'relative',
        overflow: 'hidden',
        backgroundColor: 'black',
        willChange: 'transform',
      }}
    >
      {mergedVideoData.map((video, index) => {
        const isLastVideo = index === mergedVideoData.length - 1;
        const start = mergedVideoData
          .slice(0, index)
          .reduce((acc, curr) => acc + curr.duration, 0);
        const nextVideo =
          index < mergedVideoData.length - 1
            ? mergedVideoData[index + 1]
            : null;
        // 确保当前视频的持续时间包含了所有音频的时长
        const currentVideoEnd = video.duration;

        return (
          <Fragment key={index}>
            <Sequence
              from={start}
              durationInFrames={
                video.duration +
                (video.transition?.enabled ? video.transition.duration || 8 : 0)
              }
            >
              <div
                style={{
                  width: '100%',
                  height: '100%',
                  position: 'relative',
                  overflow: 'hidden',
                  backfaceVisibility: 'hidden',
                  perspective: 1000,
                  ...getTransitionStyles(
                    frame,
                    start,
                    currentVideoEnd,
                    isLastVideo,
                    video.transition,
                  ),
                }}
              >
                {/* 当前视频容器 */}
                <div
                  style={{
                    position: 'absolute',
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    transform: 'translate3d(0, 0, 0)',
                    backfaceVisibility: 'hidden',
                  }}
                >
                  <Video
                    muted
                    src={video.video}
                    style={getVideoStyle(
                      video.rotation,
                      index,
                      index === mergedVideoData.length - 1,
                    )}
                    preload="auto"
                  />
                </div>

                {/* 下一个视频容器 - 最后一个视频不需要 */}
                {nextVideo && !isLastVideo && (
                  <div
                    style={{
                      position: 'absolute',
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      transform: 'translate3d(0, 0, 0)',
                      backfaceVisibility: 'hidden',
                      ...getNextVideoTransitionStyles(
                        frame,
                        start,
                        currentVideoEnd,
                        video.transition,
                      ),
                    }}
                  >
                    <Video
                      muted
                      src={nextVideo.video}
                      style={getVideoStyle(
                        nextVideo.rotation,
                        index + 1,
                        index + 1 === mergedVideoData.length - 1,
                      )}
                    />
                  </div>
                )}

                {/* 预加载下一个视频 */}
                {nextVideo && (
                  <Video
                    src={nextVideo.video}
                    style={{ display: 'none' }}
                    muted
                  />
                )}

                {/* 文本容器 */}
                <div
                  style={{
                    position: 'absolute',
                    bottom: '20%',
                    left: 0,
                    right: 0,
                    zIndex: 2,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    padding: '0 20px',
                    ...getTextTransitionStyles(
                      frame,
                      start,
                      currentVideoEnd,
                      isLastVideo,
                      video.transition,
                    ),
                  }}
                >
                  <div
                    style={{
                      width: '100%',
                      textAlign: 'center',
                      transition: 'transform 0.3s ease-out',
                    }}
                  >
                    {video.animation ? (
                      <VideoText
                        splitTexts={video.splitTexts}
                        highlightTexts={video.highlightTexts || []}
                        style={{
                          ...(textConfigs[index]?.style || {}),
                          fontSize: '32px',
                          textShadow: '0 2px 4px rgba(0,0,0,0.5)',
                        }}
                      />
                    ) : (
                      <VideoSplitText
                        splitTexts={video.splitTexts}
                        highlightTexts={video.highlightTexts}
                        style={{
                          ...(textConfigs[index]?.style || {}),
                          fontSize: '32px',
                          textShadow: '0 2px 4px rgba(0,0,0,0.5)',
                        }}
                      />
                    )}
                  </div>
                </div>
                {/* 修改音频播放逻辑 */}
                {video.audios?.map((audioConfig, audioIndex) => (
                  <Audio
                    key={`audio-${audioIndex}`}
                    src={audioConfig.audioUrl}
                    volume={audioConfig.volume || VOICE_VOLUME}
                    startFrom={audioConfig.startFrom}
                  />
                ))}
              </div>
            </Sequence>
          </Fragment>
        );
      })}
      {/* 背景音乐 - 调整音量 */}
      <Audio src={bgAudio} volume={BG_MUSIC_VOLUME} />
    </div>
  );
};

// 修改总时长计算，使用固定的 fps
// export const videoDuration = (6 + 8 + 5 + 4 + 24 + 12) * 30; // 总秒数 * 默认fps
